package com.findyou.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.findyou.utils.JwtHelper;
import com.findyou.utils.Result;
import com.findyou.utils.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Title: LoginProtectedInterceptor
 * @Author 贾金博
 * @Package com.findyou.interceptors
 * @Date 2024/3/8 19:05
 * @description: 登录拦截器 检查请求头是否包含有效的token
 * 有效的话 就放行
 * 没有 或者无效 就返回到登录界面 504 客户端就知道什么意思了
 */
@Component
public class LoginProtectedInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token"); // 得到请求头里面的token
        boolean expiration = jwtHelper.isExpiration(token);
        if (!expiration) {
            // 放行 表示没有过期
            return true;
        }
        //返回504的错误信息
        Result result = Result.build(null, ResultCodeEnum.NOTLOGIN);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(request);
        response.getWriter().print(json);


        return false;
    }
}
